<?php
/**
 *                          _ooOoo_
 *                         o8888888o
 *                         88" . "88
 *                         (| -_- |)
 *                         O\  =  /O
 *                      ____/`---'\____
 *                    .'  \|     |//  `.
 *                   /  \|||  :  |||//  \
 *                  /  _||||| -:- |||||-  \
 *                  |   | \\  -  /// |   |
 *                  | \_|  ''\---/''  |   |
 *                  \  .-\__  `-`  ___/-. /
 *                ___`. .'  /--.--\  `. . __
 *             ."" '<  `.___\_<|>_/___.'  >'"".
 *            | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *            \  \ `-.   \_ __\ /__ _/   .-` /  /
 *       ======`-.____`-.___\_____/___.-`____.-'======
 *                          `=---='
 *
 *==================================================
 *                  佛祖保佑        永无BUG
 *         佛曰:
 *                写字楼里写字间，写字间里程序员；
 *                程序人员写程序，又拿程序换酒钱。
 *                酒醒只在网上坐，酒醉还来网下眠；
 *                酒醉酒醒日复日，网上网下年复年。
 *                但愿老死电脑间，不愿鞠躬老板前；
 *                奔驰宝马贵者趣，公交自行程序员。
 *                别人笑我忒疯癫，我笑自己命太贱；
 *                不见满街漂亮妹，哪个归得程序员？
 *==================================================
 */

 
/**
 * 苦令营报告配置
 * @author  Snow
 * @date    2019-05-24
 */
namespace App\Admin\Controllers\kly;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\kly\kly_setting;

class CampSettingController extends Controller
{

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('报告维度');
            $content->description('配置');
            
            $content->body($this->grid()->render());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('大营');
            $content->description(trans('admin.edit'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('大营');
            $content->description(trans('admin.create'));

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $data = DB::table('kly_setting as ks')
            ->join('kly_camps as kc','kc.id','=','ks.camp_id')
            ->where('ks.pid',0)
            ->get(['kc.name','ks.id','ks.status','ks.cover','ks.background']);

        $camp_data = DB::table('kly_setting')->where('pid','>',0)
            ->groupby('pid')->select('pid',DB::raw("group_concat(name) as name"))->get();

        $data = json_decode(json_encode($data),true);
        $camp_data = json_decode(json_encode($camp_data),true);

        $temp = array();
        foreach($camp_data as $v){
            $temp[$v['pid']] = $v['name'];
        }

        foreach($data as $k=>$v){
            if(isset($temp[$v['id']])){
                $data[$k]['item'] = $temp[$v['id']];
            }
        }

        return view('admin.kly.setting_table',compact('data'));
/*        return Admin::grid(Camp::class, function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->id(trans('admin.ID'))->sortable();
            $grid->name(trans('admin.name'));
            $grid->start_date('开始时间');
            
            
            $grid->end_date('结束时间');
            $grid->status(trans('admin.status'))->editable('select', [0 => '启用', 1 => '禁用']);
            
            $grid->actions(function ($actions) {
                $actions->disableView();
            });

            //禁用导出按钮
            $grid->disableExport();
            //禁用筛选按钮
            $grid->disableFilter();

            $grid->tools(function ($tools) { 
                //关闭批量删除 
                $tools->batch(function ($batch) { 
                    $batch->disableDelete(); 
                });
            });
        });*/
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Camp::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->text('name','名称')->rules('required')->addElementLabelClass('must-input');
            $form->date('start_date', '开始时间')->format('YYYY-MM-DD')->rules('required')->addElementLabelClass('must-input');
            $form->date('end_date', '结束时间')->format('YYYY-MM-DD')->rules('required')->addElementLabelClass('must-input');
            $form->radio('status', trans('admin.status'))->options([0 => trans('admin.enable'), 1 => trans('admin.disable')])->default(0);
            
            //去掉添加/编辑表单的重置按钮
            $form->disableReset();
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
        });
    }

    public function setting_create(Content $content)
    {
        $content->header('配置');
        $content->description('添加');

        $camps = DB::table('kly_camps')->where('camp_type','1')
            ->whereRaw('find_in_set('.Admin::user()->id.',`leaders`)')->get();
        $content->body(view('admin.kly.setting_create',compact('camps')));
        return $content;
    }

    public function setting_save(Request $request)
    {
        $data = array();
        $req = json_decode(request('request'),true);
        foreach($req as $key => $v){
            $data[$key] = $v;
        }

        $camp = $data['camp'];
        $color = $data['color'];
        unset($data['camp']);
        unset($data['color']);

        $insert = array();
        $insert['pid'] = 0;
        $insert['camp_id'] = $camp;
        $insert['status'] = '0';
        $insert['color'] = $color;

        $count = DB::table('kly_setting')->where('camp_id',$camp)->count();
/*        if($count > 0){
            return array('status'=>-1,'message'=>'该营配置已经存在！');
        }*/

        $file = $request->file('cover');
        $destinationPath = '/upload/kly';
        if (is_null($file)) {
            $filePath = null;
        }else{
            // public文件夹下面uploads/xxxx-xx-xx 建文件夹
            $extension = $file->getClientOriginalExtension();   // 上传文件后缀
            $fileName = date('YmdHis').mt_rand(100,999).'.'.$extension; // 重命名
            $file->move(public_path().$destinationPath, $fileName); // 保存图片
            $insert['cover'] = $destinationPath.'/'.$fileName;
        }

        $file = $request->file('background');
        if (is_null($file)) {
            $filePath = null;
        }else{
            $extension = $file->getClientOriginalExtension();   // 上传文件后缀
            $fileName = date('YmdHis').mt_rand(100,999).'.'.$extension; // 重命名
            $file->move(public_path().$destinationPath, $fileName); // 保存图片
            $insert['background'] = $destinationPath.'/'.$fileName;
        }

        DB::beginTransaction();
        try{
            $id = DB::table('kly_setting')->insertGetId($insert);
            $insert = array();

            foreach($data as $k => $v){
                $temp = array();
                //整体启用的才插入数据库
                if(isset($v['data'][$k.'_status']) && $v['data'][$k.'_status'] == 'on'){
                    $temp['pid'] = $id;
                    $temp['name'] = $v['name'];
                    $temp['tag'] = $k;

                    //类型在作业、家校、测试、听写中的，只要设置了总分，即启用
                    //其它类型，启用且设置了总分
                    //剩下的标记为没有启用分数选项
                    if(in_array($k,['zuoye','jiaxiao','test','dictation'])){
                        if(!is_null($v['data'][$k.'_total_score'])){
                            $temp['total_score'] = $v['data'][$k.'_total_score'];
                            $temp['score_status'] = '1';
                        }
                    }else if(isset($v['data'][$k.'_score']) && $v['data'][$k.'_score'] == 'on'){
                        $temp['total_score'] = $v['data'][$k.'_total_score'];
                        $temp['score_status'] = '1';
                    }else{
                        $temp['score_status'] = '0';
                    }

                    //这五个状态已经定义好了，启用即可
                    //新增项的如果启用了状态，还要把状态一起插入
                    if(in_array($k,['kaoqin','zuoye','jiaxiao','test','dictation'])){
                        $temp['use_status'] = '1';
                    }elseif(isset($v['data'][$k.'_score_status']) && $v['data'][$k.'_score_status'] == 'on'){
                        $temp['use_status'] = '1';
                        $status = array();
                        $status = json_decode($v['status'],true);
                        $status_arr = array();
                        foreach($status as $_v){
                            $status_arr[] = explode('——',$_v)[1];
                        }
                        $temp['status_item'] = json_encode($status_arr);
                    }else{
                        $temp['use_status'] = '0';
                    }


                    //插入周期。每天的不用管，自定义的要把时间额外插入
                    if(isset($v['data'][$k.'_time']) && $v['data'][$k.'_time'] == 'everyday'){
                        $temp['time_status'] = '1';
                    }elseif(isset($v['data'][$k.'_time']) && $v['data'][$k.'_time'] == 'custom'){
                        $temp['time_status'] = '0';
                        $time = array();
                        $time = json_decode($v['time'],true);
                        $time_arr = array();
                        foreach($time as $_v){
                            $time_arr[] = explode('——',$_v)[1];
                        }
                        $temp['time'] = json_encode($time_arr);
                    }
                }
                $insert[] = $temp;
            }
            foreach($insert as $value){
                DB::table('kly_setting')->insert($value);
            }
            DB::commit();
        }catch(Exception $e){
            DB::rollBack();
            return array('status'=>-1,'message'=>$e->getMessage());
        }

        return array('status'=>1,'message'=>'操作成功');
    }

    public function setting_delete(Request $request){
        DB::beginTransaction();
        try{
            DB::table('kly_setting')->where('id',$request['id'])->delete();
            DB::table('kly_setting')->where('pid',$request['id'])->delete();
            DB::commit();
        }catch(Exception $e){
            DB::rollBack();
            return array('status'=>-1,'message'=>$e->getMessage());
        }

        return array('status'=>1,'message'=>'操作成功');
    }

    public function updown(Request $request){
        DB::beginTransaction();
        try{
            $this->createNotice($request['id']);
        }catch(Exception $e){
            DB::rollBack();
            return array('status'=>-1,'message'=>$e->getMessage());
        }
        DB::commit();
        return array('status'=>1,'message'=>'操作成功');
    }

    public function createNotice($id)
    {
        $id = intval($id);
        $big_camp = DB::table('kly_setting as ks')->join('kly_camps as kc','kc.id','=','ks.camp_id')->where('ks.id',$id)
            ->get(['ks.id','ks.camp_id','kc.name']);
        $big_camp = json_decode(json_encode($big_camp),true);


        $kly_setting = DB::table('kly_setting')->where('pid',$id)->get();
        $kly_setting = json_decode(json_encode($kly_setting),true);

        $small_camps = DB::table('kly_camps')->where('pid',$big_camp[0]['camp_id'])->get();
        $small_camps = json_decode(json_encode($small_camps),true);

        $insert = array();

        $time_arr = array();
        $start_date = DB::table('kly_terms')->where('status','1')->get(['start_date','end_date']);
        $start_date = json_decode(json_encode($start_date),true);
        $time_arr[0] = $start_date[0]['start_date']." 00:00:00";
        for($i=1;$i<=18;$i++){
            $time_arr[] = date("Y-m-d H:i:s",strtotime($time_arr[$i-1].'+1 day'));
        }

        $data = array();
//第一次拼装数据
        foreach($kly_setting as $v){
            if($v['tag'] == 'radar'){
                continue;
            }
            $temp = array();

            switch($v['tag']){
                case 'kaoqin':
                    $temp['notice_type'] = '1';
                    $temp['event'] = '考勤';
                    break;
                case 'test':
                    $temp['notice_type'] = '2';
                    $temp['event'] = '测试';
                    break;
                case 'jiaxiao':
                    $temp['notice_type'] = '3';
                    $temp['event'] = '家校';
                    break;
                case 'dictation':
                    $temp['notice_type'] = '4';
                    $temp['event'] = '听写';
                    break;
                case 'zuoye':
                    $temp['notice_type'] = '5';
                    $temp['event'] = '作业';
                    break;
                default:
                    $temp['notice_type'] = '6';
                    $temp['event'] = $v['name'];
                    break;
            }

            if($v['use_status'] == '1' && $v['score_status'] != '1'){
                $temp['type'] = '1';
            }elseif($v['use_status'] != '1' && $v['score_status'] == '1'){
                $temp['type'] = '2';
            }elseif($v['use_status'] == '1' && $v['score_status'] == '1'){
                $temp['type'] = '3';
            }

            if($v['score_status'] == '1'){
                $temp['total_score'] = $v['total_score'];
            }else{
                $temp['total_score'] = NULL;
            }

            $temp['status'] = '1';
            $temp['name'] = $v['name'];
            $temp['tag'] = $v['tag'];
            $temp['setting_id'] = $v['id'];


            if($v['time_status'] == '1'){
                $t = 1;
                foreach($time_arr as $_value){
                    $temp['starttime'] = $_value;
                    $temp['endtime'] = date("Y-m-d H:i:s",strtotime($_value."+3 day"));
                    $temp['times'] = $t;
                    $data[] = $temp;
                    $t++;
                }
            }elseif($v['time_status'] == '0'){
                $time = json_decode($v['time'],true);
                $t = 1;
                foreach($time as $_value){
                    $temp['starttime'] = date("Y-m-d 00:00:00",strtotime($_value));
                    $temp['endtime'] = date("Y-m-d H:i:s",strtotime($_value."+3 day"));
                    $temp['times'] = $t;
                    $data[] = $temp;
                    $t++;
                }
            }
        }

        foreach($small_camps as $v){
            foreach($data as $_k=>$_v){
                $temp = array();
                $temp['tutor_id'] = $v['tutors'];
                $temp['aids'] = $v['aids'];
                $temp['event'] =$_v['event'].'-'.$v['name'].'/'.date("Y-m-d",strtotime($_v['starttime']));
                $temp['camp_id'] = $v['id'];
                $insert[] = array_merge($_v,$temp);
            }
        }
        DB::table('kly_setting')->where('id',$id)->update(['status'=>'1']);
        DB::table('kly_notice')->insert($insert);
    }
}